import * as base from "./base.js";
import instance from './request.js';
import { $, $$ } from './base.js';


window.addEventListener('load', function () {
    //跳转到发布房源页面
    if (localStorage.getItem('identity') == 2) {
        $('.add_fangyuan').style.display = 'block';
    }

    base.navbox();
    base.avatarimg();

    let collectionid = localStorage.getItem('collectionid');
    console.log(collectionid);
    let houseid = [];

    $('.wishdetail_name').innerHTML = localStorage.getItem('collectionname');



    instance.get(`/collection/${collectionid}`, {
        headers: {
            'Authorization': window.localStorage.getItem('token'),
            'Content-Type': 'application/json',
        }
    }).then(response => {
        let wisharr = response.data.data;
        console.log(wisharr);


        if (wisharr) {
            wisharr.homes.forEach(function (value, index, array) {
                let str = `
                <div class="del_wishbox_li wishdetail_li" id="${wisharr.homes[index].id}" data-addnote=${(wisharr.homes[index].remark.content) ? (wisharr.homes[index].remark.id) : ''}>
                <div class="wishdetail_mask" id="${wisharr.homes[index].id}"></div>
                            <div class="wishdetail_love">
                                <div class="wishdetail_love_mask"></div>
                                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" aria-hidden="true"
                                    role="presentation" focusable="false"
                                    style="display: block; fill: #ff385c; height: 24px; width: 24px; stroke: var(--f-mkcy-f); stroke-width: 2; overflow: visible;"
                                    id="5">
                                    <path
                                        d="M16 28c7-4.73 14-10 14-17a6.98 6.98 0 0 0-7-7c-1.8 0-3.58.68-4.95 2.05L16 8.1l-2.05-2.05a6.98 6.98 0 0 0-9.9 0A6.98 6.98 0 0 0 2 11c0 7 7 12.27 14 17z"
                                        class="lazyimg_svg" style="stroke: white;
                                    stroke-width: 2px;" id="5" data-color="0"></path>
                                </svg>
                            </div>
                            <div class="del_wishbox_li_t wishdetail_li_t">
                                <div class="del_wishbox_li_tn wishdetail_li_tn" style="background: url(${(wisharr.homes[index].pictures) ? (wisharr.homes[index].pictures[0]) : ('http://43.139.230.42:8001/picture/3')}) ;background-size: 240px 240px;" data-url="${(wisharr.homes[index].pictures) ? (wisharr.homes[index].pictures[0]) : ('http://43.139.230.42:8001/picture/3')}">
                                </div>
                            </div>
                            <div class="del_wishbox_li_b" style="position: relative;">
                                <div class="del_wishbox_stars">
                                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" aria-hidden="true" role="presentation" focusable="false" style="display: block; height: 12px; width: 12px; fill: currentcolor;"><path fill-rule="evenodd" d="m15.1 1.58-4.13 8.88-9.86 1.27a1 1 0 0 0-.54 1.74l7.3 6.57-1.97 9.85a1 1 0 0 0 1.48 1.06l8.62-5 8.63 5a1 1 0 0 0 1.48-1.06l-1.97-9.85 7.3-6.57a1 1 0 0 0-.55-1.73l-9.86-1.28-4.12-8.88a1 1 0 0 0-1.82 0z"></path></svg>
                                    <span class="del_wishbox_star">${wisharr.homes[index].star ? wisharr.homes[index].star : '0'}</span>
                                </div >
                                <div class="del_wishbox_li_b_t ellipsis" style="width: 180px; font-size: 16px;">${wisharr.homes[index].title}</div>
                                <div class="del_wishbox_li_b_b ellipsis" style="width: 190px;font-size: 14px;">房源被评价数为${wisharr.homes[index].reviewCount}条</div>
                            </div >
                    ${(wisharr.homes[index].remark.content) ? `<div class="add_remarks" style="display: none;">添加备注</div>
                            <div class="add_remarkss" style="display: block;"> <span class="add_remarknote" id="${wisharr.homes[index].remark.id}">${wisharr.homes[index].remark.content}</span> <span class="add_note">编辑</span> </div>` : `<div class="add_remarks" style="display: block;">添加备注</div>
                            <div class="add_remarkss" style="display: none;"> <span class="add_remarknote"></span> <span class="add_note">编辑</span> </div>`}

                        </div > `
                $('.wishcreate_ul').insertAdjacentHTML('beforeend', str);


                //房源id数组
                houseid.push(wisharr.homes[index].id);
            })
        } else {
            $('.empty_wishdetail').style.display = 'block';
        }
    })

    $('.back_wish').addEventListener('click', function () {
        history.go(-1);
    })



    //图片加载不出来
    $('.wishcreate_ul').addEventListener('error', function (event) {
        if (event.target.tagName === 'IMG') {
            console.log('图片加载不出来');
            event.target.src = event.target.src;
        }
    });



    //添加备注
    let remark_homeid = 0;
    let target_li = 0;
    let submit = 0;
    $('.wishcreate_ul').addEventListener("click", function (event) {
        const targetElement = event.target;

        if (targetElement.classList.contains('add_remarks')) {
            console.log(1);
            target_li = targetElement.parentNode;
            $('.wishmask').style.display = 'block';
            $('.add_remarkbox').style.display = 'block';
            $('.add_remarkbox').classList.add('slidedownup');
            $('.add_remarkbox_text textarea').value = '';
            $('.add_remarkbox_b_b_r').style.backgroundColor = '#ddd';

            console.log(targetElement.parentNode.children[1].children[0]);

            $('.add_remarkbox_m_l img').src = targetElement.parentNode.children[2].children[0].getAttribute('data-url');
            console.log(targetElement.parentNode.children[3].children[0].children[1].innerHTML);
            $('.del_wishbox_starsss').innerHTML = targetElement.parentNode.children[3].children[0].children[1].innerHTML;
            console.log($('.del_wishbox_star').innerHTML);
            $('.add_remarkbox_m_title').innerHTML = targetElement.parentNode.children[3].children[1].innerHTML;
            $('.add_remarkbox_m_content').innerHTML = targetElement.parentNode.children[3].children[2].innerHTML;
            remark_homeid = targetElement.parentNode.getAttribute('id');



            control(0, 1);
        }

        if (targetElement.classList.contains('add_note')) {
            target_li = targetElement.parentNode.parentNode;
            $('.wishmask').style.display = 'block';
            $('.add_remarkbox').style.display = 'block';
            $('.add_remarkbox').classList.add('slidedownup');
            $('.add_remarkbox_text textarea').value = targetElement.parentNode.children[0].innerHTML;
            $('.add_remarkbox_b_b_r').style.backgroundColor = '#ddd';

            console.log(targetElement.parentNode.parentNode.children[1].children[0]);

            $('.add_remarkbox_m_l img').src = targetElement.parentNode.parentNode.children[2].children[0].getAttribute('data-url');
            $('.del_wishbox_starsss').innerHTML = targetElement.parentNode.parentNode.children[3].children[0].children[1].innerHTML;
            $('.add_remarkbox_m_title').innerHTML = targetElement.parentNode.parentNode.children[3].children[1].innerHTML;
            $('.add_remarkbox_m_content').innerHTML = targetElement.parentNode.parentNode.children[3].children[2].innerHTML;
            remark_homeid = targetElement.parentNode.parentNode.getAttribute('id');


            control(targetElement.parentNode.children[0].innerHTML, 2);

        }



        //跳转到详情页
        if (targetElement.classList.contains('wishdetail_mask')) {
            localStorage.setItem('detailid', targetElement.getAttribute('id'));

            location.href = 'fangyuan.html';
        }


    });



    //关闭添加标签
    $('.wishmask').addEventListener('click', function () {
        if ($('.add_remarkbox').style.display == 'block') {
            $('.add_remarkbox_close').click();
        } else if ($('.delcha_whish').style.display == 'block') {
            $('.delcha_whish_close').click();
        } else if ($('.change_wish').style.display == 'block') {
            $('.change_wish_close').click();
        } else if ($('.delete_wish').style.display == 'block') {
            $('.delete_wish .delete_wish_close').click();
        }


    })
    $('.add_remarkbox_close').addEventListener('click', function () {
        $('.wishmask').style.display = 'none';
        $('.add_remarkbox').style.display = 'none';
    })





    //添加备注的控制字数
    function control(num, index) {
        let count = $('.add_remarkbox_text textarea').value.length;
        $('.add_remarkbox_textm .min_num').textContent = count;
        $('.add_remarkbox_text textarea').oninput = function () {
            count = $('.add_remarkbox_text textarea').value.length;
            $('.add_remarkbox_textm .min_num').textContent = count;

            if (count >= parseInt($('.add_remarkbox_textm .max_num').textContent)) {
                // 如果超过最大字数限制，则截断输入
                $('.add_remarkbox_text textarea').value = $('.add_remarkbox_text textarea').value.slice(0, parseInt($('.add_remarkbox_textm .max_num').textContent - 1));
            }

            if (count == num) {
                $('.add_remarkbox_b_b_r').style.backgroundColor = '#ddd';
            } else if ($('.add_remarkbox_text textarea').value == num) {
                $('.add_remarkbox_b_b_r').style.backgroundColor = '#ddd';
            } else {
                $('.add_remarkbox_b_b_r').style.backgroundColor = '#222';
                if (index == 1) {
                    submit = 1;
                } else {
                    submit = 2;
                }
            }
        };
    }


    //发送添加备注请求
    function addnote() {
        instance.post('/remark', {
            collectionId: collectionid,
            homeId: remark_homeid,
            remark: $('.add_remarkbox_text textarea').value
        }, {
            headers: {
                'Authorization': window.localStorage.getItem('token'),
                'Content-Type': 'application/json',
            }
        }).then(response => {
            console.log(response.data.data);
            let addarr = response.data.data;

            console.log(target_li);
            target_li.setAttribute('data-addnote', addarr.id);
            target_li.children[4].style.display = 'none';
            target_li.children[5].style.display = 'block';
            target_li.children[5].children[0].innerHTML = $('.add_remarkbox_text textarea').value;
            $('.add_remarkbox_text textarea').value = '';
            $('.add_remarkbox_b_b_r').style.backgroundColor = '#ddd';



            $('.add_remarkbox_close').click();
            submit = 0;



        }).catch(error => {
            console.error(error)
        })
    }
    function changenote() {
        instance.post('/remark/update', {
            remarkId: target_li.getAttribute('data-addnote'),
            content: $('.add_remarkbox_text textarea').value
        }, {
            headers: {
                'Authorization': window.localStorage.getItem('token'),
                'Content-Type': 'application/json',
            }
        }).then(response => {
            console.log(response.data);
            let addarr = response.data.data;


            target_li.children[5].children[0].innerHTML = $('.add_remarkbox_text textarea').value;



            $('.add_remarkbox_close').click();
            submit = 0;



        }).catch(error => {
            console.error(error)
        })
    }
    function delnote() {
        instance({
            url: `/remark`,
            method: 'DELETE',
            data: {
                remarkId: target_li.getAttribute('data-addnote')
            },
            headers: {
                'Authorization': window.localStorage.getItem('token'),
                'Content-Type': 'application/json',
            }
        }).then(response => {
            console.log(response);

            target_li.children[4].style.display = 'block';
            target_li.children[5].style.display = 'none';

            submit = 0;
            $('.add_remarkbox_close').click();


        }).catch(error => {
            console.error(error)
        })
    }
    $('.add_remarkbox_b_b_r').addEventListener('click', base.debounce(function () {
        console.log(submit);
        if (submit == 1) {
            addnote();
        } else if ($('.add_remarkbox_text textarea').value == '') {
            delnote();
        } else if (submit == 2 && $('.add_remarkbox_text textarea').value != '') {
            changenote();
        }

    })
    )




    //删除与修改心愿单
    $('.wish_detail').addEventListener('click', function () {
        $('.wishmask').style.display = 'block';
        $('.delcha_whish').style.display = 'block';
        $('.delcha_whish').classList.add('slidedownup');
    })

    //关闭删除与修改
    $('.delcha_whish_close').addEventListener('click', function () {
        $('.wishmask').style.display = 'none';
        $('.delcha_whish').style.display = 'none';
    })


    //修改心愿单
    $('.delcha_whish_b_t_mask').addEventListener('click', function () {
        $('.delcha_whish').style.display = 'none';
        $('.change_wish').style.display = 'block';

        $('.change_wish_input input').value = $('.wishdetail_name').innerHTML;
        $('.change_wish_name').style.transform = 'scale(0.8) translateX(-10px) translateY(-15px)';
        $('.change_wish_num .min_num').textContent = $('.change_wish_input input').value.length;
    })

    //限制字数
    $('.change_wish_input input').addEventListener('input', function () {
        const count = $('.change_wish_input input').value.length;
        $('.change_wish_num .min_num').textContent = count;

        if (count >= parseInt($('.change_wish_num .max_num').textContent)) {
            // 如果超过最大字数限制，则截断输入
            $('.change_wish_input input').value = $('.change_wish_input input').value.slice(0, parseInt($('.change_wish_num .max_num').textContent - 1));
        }
    });


    $('.change_wish_input input').addEventListener('focus', function () {
        $('.change_wish_name').style.transform = 'scale(0.8) translateX(-10px) translateY(-15px)';
        $('.change_wish_input').style.border = '1px solid #222';
    })
    $('.change_wish_input input').addEventListener('blur', function () {
        $('.change_wish_input').style.border = '1px solid #b0b0b0';
        if (!($('.change_wish_input input').value)) {
            $('.change_wish_name').style.transform = 'scale(1) translateX(0px) translateY(0px)';
        }
    })


    //修改的完成键
    $('.change_wish_b_r').addEventListener('click', base.debounce(function () {
        if ($('.change_wish_input input').value != $('.wishdetail_name').innerHTML) {
            instance.post('/collection/update', {
                collectionId: collectionid,
                name: $('.change_wish_input input').value
            }, {
                headers: {
                    'Authorization': window.localStorage.getItem('token'),
                    'Content-Type': 'application/json',
                }
            }).then(response => {

                $('.wishdetail_name').innerHTML = $('.change_wish_input input').value;
                $('.wishmask').style.display = 'none';
                $('.change_wish').style.display = 'none';
                localStorage.setItem('collectionname', $('.change_wish_input input').value);

                base.tooltipBox('', '重命名成功!', '1');


            }).catch(error => {
                console.error(error)
            })
        }
    })
    )

    //关闭修改心愿单
    $('.change_wish_close').addEventListener('click', function () {
        $('.delcha_whish').style.display = 'block';
        $('.change_wish').style.display = 'none';
    })
    $('.change_wish_b_l').addEventListener('click', function () {
        $('.change_wish_close').click();
    })






    //删除心愿单
    $('.delcha_whish_b_b_mask').addEventListener('click', function () {
        $('.delcha_whish').style.display = 'none';
        $('.delete_wish').style.display = 'block';
        $('.delete_wish_name').innerHTML = $('.wishdetail_name').innerHTML;
    })

    $('.delete_wish_b_r').addEventListener('click', base.debounce(function () {
        instance({
            url: `/collection`,
            method: 'DELETE',
            data: {
                collectionId: collectionid
            },
            headers: {
                'Authorization': window.localStorage.getItem('token'),
                'Content-Type': 'application/json',
            }
        }).then(response => {
            console.log(response);
            base.tooltipBox('', '删除成功!', '1');

            location.href = 'wish.html';
        }).catch(error => {
            console.error(error)
        })
    })
    )

    // 关闭删除心愿单
    $('.delete_wish .delete_wish_close').addEventListener('click', function () {
        $('.delcha_whish').style.display = 'block';
        $('.delete_wish').style.display = 'none';
    })
    $('.delete_wish_b_l').addEventListener('click', function () {
        $('.delete_wish .delete_wish_close').click();
    })






    //取消心愿单中的收藏
    let wishdetail_svg = 0;
    $(".wishcreate_ul").addEventListener("click", function (event) {
        const targetElement = event.target;


        if (targetElement.classList.contains('lazyimg_svg')) {
            if (wishdetail_svg == 0) {
                instance({
                    url: `/collection/home`,
                    method: 'DELETE',
                    data: {
                        collectionId: collectionid,
                        homeId: targetElement.parentNode.parentNode.parentNode.getAttribute('id')
                    },
                    headers: {
                        'Authorization': window.localStorage.getItem('token'),
                        'Content-Type': 'application/json',
                    }
                }).then(response => {
                    console.log(response);
                    base.tooltipBox('', '取消收藏成功!', '1');

                    targetElement.style.fill = 'rgba(0, 0, 0, 0.5)';
                    wishdetail_svg = 1;

                }).catch(error => {
                    console.error(error)
                })
            } else {
                instance({
                    url: `/collection/home`,
                    method: 'POST',
                    data: {
                        collectionId: collectionid,
                        homeId: targetElement.parentNode.parentNode.parentNode.getAttribute('id')
                    },
                    headers: {
                        'Authorization': window.localStorage.getItem('token'),
                        'Content-Type': 'application/json',
                    }
                }).then(response => {
                    console.log(response);
                    base.tooltipBox('', '收藏成功!', '1');

                    targetElement.style.fill = '#ff385c';
                    wishdetail_svg = 0;

                }).catch(error => {
                    console.error(error)
                })
            }

        }




    });




    //按照人数查找
    $('.wishdetail_addman').addEventListener('click', function () {
        $('.w_renshubox').style.display = 'block';

    })


    //关闭查找框
    $('.w_renshubox_close').addEventListener('click', function () {
        console.log(3);
        $('.w_renshubox').style.display = 'none';
    })

    let renshunum = 1;
    function ren_r(index, num) {
        $$('.ren_add')[index].addEventListener('click', function () {
            if (renshunum == 16 - 1) {
                $$('.ren_add')[0].style.border = '1px solid #b2dadb';
                $$('.ren_add svg')[0].style.fill = '#b2dadb';
                $$('.ren_add')[1].style.border = '1px solid #b2dadb';
                $$('.ren_add svg')[1].style.fill = '#b2dadb';
                $$('.ren_tenant')[index].innerHTML++;
                if ($$('.ren_tenant')[index].innerHTML != num) {
                    $$('.ren_reduce')[index].style.border = '1px solid #008489';
                    $$('.ren_reduce svg')[index].style.fill = '#008489';
                }


                renshunum++;
            } else if (renshunum < 16 - 1) {
                $$('.ren_reduce')[index].style.border = '1px solid #008489';
                $$('.ren_reduce svg')[index].style.fill = '#008489';
                $$('.ren_tenant')[index].innerHTML++;

                renshunum++;
            }
            console.log(renshunum);

        })

    }
    ren_r(0, 1);
    ren_r(1, 0);


    function ren_l(index, num) {
        $$('.ren_reduce')[index].addEventListener('click', function () {
            if (renshunum > 1 && ($$('.ren_tenant')[index].innerHTML > num + 1)) {
                $$('.ren_add')[0].style.border = '1px solid #008489';
                $$('.ren_add svg')[0].style.fill = '#008489';
                $$('.ren_add')[1].style.border = '1px solid #008489';
                $$('.ren_add svg')[1].style.fill = '#008489';

                $$('.ren_tenant')[index].innerHTML--;

                renshunum--;
            } else if ($$('.ren_tenant')[index].innerHTML == num + 1) {
                $$('.ren_reduce')[index].style.border = '1px solid #b2dadb';
                $$('.ren_reduce svg')[index].style.fill = '#b2dadb';
                $$('.ren_tenant')[index].innerHTML--;

                renshunum--;
            }
            console.log(renshunum);
        })

    }
    ren_l(0, 1);
    ren_l(1, 0);



    $$('.ren_add')[2].addEventListener('click', function () {
        if ($$('.ren_tenant')[2].innerHTML == 5 - 1) {
            $$('.ren_add')[2].style.border = '1px solid #b2dadb';
            $$('.ren_add svg')[2].style.fill = '#b2dadb';
            $$('.ren_tenant')[2].innerHTML++;
            return;
        } else if ($$('.ren_tenant')[2].innerHTML < 5 - 1) {
            $$('.ren_reduce')[2].style.border = '1px solid #008489';
            $$('.ren_reduce svg')[2].style.fill = '#008489';
            $$('.ren_tenant')[2].innerHTML++;
        }
    })
    $$('.ren_reduce')[2].addEventListener('click', function () {
        if ($$('.ren_tenant')[2].innerHTML == 1) {
            $$('.ren_reduce')[2].style.border = '1px solid #b2dadb';
            $$('.ren_reduce svg')[2].style.fill = '#b2dadb';
            $$('.ren_tenant')[2].innerHTML--;
            return;
        } else if ($$('.ren_tenant')[2].innerHTML > 1) {
            $$('.ren_add')[2].style.border = '1px solid #008489';
            $$('.ren_add svg')[2].style.fill = '#008489';
            $$('.ren_tenant')[2].innerHTML--;
        }
    })


    $('.w_renshubox_b_r').addEventListener('click', function () {
        let num = 0;
        $('.empty_wishdetail').style.display = 'none';
        console.log(houseid);
        $$('.del_wishbox_li').forEach(function (value, index, array) {
            // value.remove();
            $$('.del_wishbox_li')[index].style.display = 'none';
        })




        houseid.forEach(function (value, index, array) {
            instance.get(`/home/detail/${value}`, {
                headers: {
                    'Authorization': window.localStorage.getItem('token'),
                    'Content-Type': 'application/json',
                }
            }).then(response => {
                let wisharr = response.data.data;
                console.log(wisharr);

                if (wisharr.tenant >= renshunum) {
                    const container = document.querySelector('.wishcreate_ul');
                    const liElement = container.querySelector(`[id = "${wisharr.id}"]`);
                    liElement.style.display = 'block';

                    num++;
                }

                if (num == 0) {
                    $('.empty_wishdetail').style.display = 'block';
                }


            })
        })

        if (renshunum > 1) {
            $('.wishdetail_addman').innerHTML = renshunum + '人';
        } else {
            $('.wishdetail_addman').innerHTML = '添加房客';
        }

        $('.w_renshubox').style.display = 'none';


    })





})


